<template>
  <div class="news-list-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">新闻管理</h1>
        </div>
        <el-button type="primary" @click="navigateTo('/admin/news/add')" class="w-[100px]">
          添加新闻
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="mb-6 search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.title" placeholder="标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="searchForm.content" placeholder="内容" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select 
            v-model="searchForm.categoryId" 
            placeholder="全部分类" 
            clearable
            filterable
            style="width: 100%"
          >
            <el-option 
              v-for="item in categories" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="来源">
          <el-select 
            v-model="searchForm.sourceId" 
            placeholder="全部来源" 
            clearable
            filterable
            style="width: 100%"
          >
            <el-option 
              v-for="item in sources" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="全部状态" 
            clearable
            filterable
            style="width: 100%"
          >
            <el-option 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="searchForm.publishTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="从"
            end-placeholder="到"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" class="w-[80px]">
            <el-icon class="mr-1"><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch" class="w-[80px]">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">新闻列表</div>
          <div class="flex space-x-2">
            <el-button size="small" @click="handleRefresh">
              刷新
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              :disabled="selectedNews.length === 0"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              :disabled="selectedNews.length === 0"
              @click="handleBatchPublish"
            >
              批量发布
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="tableLoading"
        :data="newsList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
        v-if="!pageLoading && !tableLoading && Array.isArray(newsList) && newsList.length > 0 && newsList.every(item => item && typeof item === 'object')"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="标题" min-width="300" show-overflow-tooltip></el-table-column>
        <el-table-column prop="categoryName" label="分类" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row" size="small" type="info">{{ scope.row.categoryName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sourceName" label="来源" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row" size="small" type="info">{{ scope.row.sourceName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row" 
              size="small" 
              :type="getStatusType(scope.row.status)"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isHot" label="热门" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row" 
              size="small" 
              :type="scope.row.isHot === 1 ? 'danger' : 'info'"
            >
              {{ scope.row.isHot === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180">
          <template #header>
            <div class="flex items-center cursor-pointer hover:text-blue-500 transition-colors" @click="togglePublishTimeSort">
              <span>发布时间</span>
              <div class="ml-2 text-lg font-bold">
                <span v-if="searchForm.sortField === 'publishTime'">
                  <span v-if="searchForm.sortOrder === 'asc'" class="text-blue-500">↑</span>
                  <span v-else class="text-blue-500">↓</span>
                </span>
                <span v-else class="text-gray-400">↕</span>
              </div>
            </div>
          </template>
          <template #default="scope">
            <span v-if="scope.row">{{ scope.row.publishTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div v-if="scope.row" class="flex space-x-2">
              <el-button size="small" text @click="viewNews(scope.row.id)">
                查看
              </el-button>
              <el-button size="small" text @click="editNews(scope.row.id)">
                编辑
              </el-button>
              <el-button 
                size="small" 
                text 
                type="danger" 
                @click="deleteNews(scope.row.id)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空数据状态 -->
      <div v-if="!pageLoading && !tableLoading && (!Array.isArray(newsList) || newsList.length === 0)" class="text-center py-12 text-gray-500">
        <div class="text-lg mb-2">暂无数据</div>
        <div class="text-sm">请尝试调整搜索条件或刷新页面</div>
      </div>
      
      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { adminNewsAPI, categoryAPI, sourceAPI } from '~/services/api'

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()

// 表格数据
const tableLoading = ref(false)
const pageLoading = ref(true) // 新增：页面整体加载状态
const newsList = ref([])
const selectedNews = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = ref({
  title: '',
  content: '',
  categoryId: undefined,
  sourceId: undefined,
  status: undefined,
  isHot: undefined,
  publishTimeRange: null,
  sortField: 'publishTime',
  sortOrder: 'desc'
})

// 分类和来源选项
const categories = ref([])
const sources = ref([])

const statusOptions = ref([
  { value: 1, label: '已发布' },
  { value: 0, label: '草稿' },
  { value: -1, label: '已下架' }
])

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'warning'
    case -1: return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1: return '已发布'
    case 0: return '草稿'
    case -1: return '已下架'
    default: return '未知'
  }
}

// 加载分类和来源数据
const loadOptions = async () => {
  try {
    const [categoriesData, sourcesData] = await Promise.all([
      categoryAPI.getCategories(),
      sourceAPI.getSources()
    ])
    categories.value = categoriesData
    sources.value = sourcesData
    console.log('加载选项数据成功:', {
      categories: categoriesData.length,
      sources: sourcesData.length
    })
  } catch (error) {
    console.error('加载选项数据失败:', error)
    ElMessage.error('加载选项数据失败')
  }
}

// 加载新闻数据
const loadNews = async () => {
  try {
    tableLoading.value = true
    
    // 构建查询参数
    const queryDTO = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value
    }
    
    // 处理时间范围
    if (searchForm.value.publishTimeRange && searchForm.value.publishTimeRange.length === 2) {
      // 将日期转换为ISO日期时间格式：开始日期 00:00:00，结束日期 23:59:59
      queryDTO.publishTimeStart = searchForm.value.publishTimeRange[0] + 'T00:00:00'
      queryDTO.publishTimeEnd = searchForm.value.publishTimeRange[1] + 'T23:59:59'
      delete queryDTO.publishTimeRange
    }
    
    console.log('发送查询参数:', queryDTO)
    
    const result = await adminNewsAPI.getNewsPage(queryDTO)
    
    // 确保数据是数组
    if (result && Array.isArray(result.list)) {
      // 额外检查每个项目是否有效
      const validList = result.list.filter(item => item && typeof item === 'object' && item.id)
      newsList.value = validList
      total.value = result.total || 0
          console.log('加载新闻数据成功:', { count: validList.length, total: result.total })
  } else {
    newsList.value = []
    total.value = 0
    console.warn('返回的数据格式不正确:', result)
  }
  
} catch (error) {
  console.error('加载新闻数据失败:', error)
  ElMessage.error('加载新闻数据失败')
  // 出错时清空数据
  newsList.value = []
  total.value = 0
} finally {
  tableLoading.value = false
}
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadNews()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    title: '',
    content: '',
    categoryId: undefined,
    sourceId: undefined,
    status: undefined,
    isHot: undefined,
    publishTimeRange: null,
    sortField: 'publishTime',
    sortOrder: 'desc'
  }
  currentPage.value = 1
  loadNews()
}

// 刷新数据
const handleRefresh = () => {
  loadNews()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadNews()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadNews()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedNews.value = selection
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedNews.value.length === 0) {
    ElMessage.warning('请选择要删除的新闻')
    return
  }
  
  const ids = selectedNews.value.map(item => item.id)
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedNews.value.length} 条新闻吗？此操作不可恢复。`,
    '批量删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await adminNewsAPI.batchDeleteNews(ids)
      ElMessage.success('批量删除成功')
      loadNews()
      selectedNews.value = []
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 批量发布
const handleBatchPublish = () => {
  if (selectedNews.value.length === 0) {
    ElMessage.warning('请选择要发布的新闻')
    return
  }
  
  ElMessageBox.confirm(
    `确定要发布选中的 ${selectedNews.value.length} 条新闻吗？`,
    '批量发布确认',
    {
      confirmButtonText: '确定发布',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      // 批量更新状态为已发布
      const promises = selectedNews.value.map(item => 
        adminNewsAPI.updateNewsStatus(item.id, 1)
      )
      await Promise.all(promises)
      
      ElMessage.success('批量发布成功')
      loadNews()
      selectedNews.value = []
    } catch (error) {
      console.error('批量发布失败:', error)
      ElMessage.error('批量发布失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 查看新闻
const viewNews = (id) => {
  window.open(`/news/${id}`, '_blank')
}

// 编辑新闻
const editNews = (id) => {
  navigateTo(`/admin/news/edit/${id}`)
}

// 删除新闻
const deleteNews = (id) => {
  const newsItem = newsList.value.find(item => item.id === id)
  const newsTitle = newsItem ? newsItem.title : `ID: ${id}`
  
  ElMessageBox.confirm(
    `确定要删除新闻「${newsTitle}」吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await adminNewsAPI.deleteNews(id)
      ElMessage.success('删除成功')
      loadNews()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 页面导航
const navigateTo = (path) => {
  router.push(path)
}

// 切换发布时间排序
const togglePublishTimeSort = () => {
  console.log('排序前:', {
    sortField: searchForm.value.sortField,
    sortOrder: searchForm.value.sortOrder
  })
  
  if (searchForm.value.sortField === 'publishTime') {
    // 如果已经是发布时间排序，则切换升序/降序
    searchForm.value.sortOrder = searchForm.value.sortOrder === 'asc' ? 'desc' : 'asc'
  } else {
    // 如果不是发布时间排序，则设置为发布时间降序
    searchForm.value.sortField = 'publishTime'
    searchForm.value.sortOrder = 'desc'
  }
  
  console.log('排序后:', {
    sortField: searchForm.value.sortField,
    sortOrder: searchForm.value.sortOrder
  })
  
  currentPage.value = 1
  loadNews()
}

// 获取行类名，用于扫描动画（现在通过CSS直接控制，保留方法以备后用）
const getRowClassName = ({ row, rowIndex }) => {
  return ''
}

// 初始化
onMounted(async () => {
  try {
    pageLoading.value = true
    await loadOptions()
    await loadNews()
  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面初始化失败')
  } finally {
    pageLoading.value = false
  }
})
</script>

<style scoped>
/* 表格样式优化 */
:deep(.el-table) {
  --el-table-header-bg-color: var(--el-fill-color-light) !important;
  --el-table-row-hover-bg-color: rgba(0, 0, 0, 0.02) !important;
  border-radius: 8px;
  overflow: hidden;
}


:deep(.el-card__header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}


/* 搜索卡片样式 */
.search-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(248, 250, 252, 0.8));
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}


/* 表格卡片样式 */
.table-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(248, 250, 252, 0.9));
  border: 1px solid rgba(255, 255, 255, 0.25);
  border-radius: 20px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.08);
}


/* 按钮样式优化 - 使用Element Plus默认圆角，与新闻源列表页面保持一致 */
:deep(.el-button) {
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 移除主要按钮的渐变背景，恢复原来的蓝色 */
:deep(.el-button--primary) {
  background: var(--el-color-primary);
  border: 1px solid var(--el-color-primary);
}

:deep(.el-button--primary:hover) {
  background: var(--el-color-primary-light-3);
  border: 1px solid var(--el-color-primary-light-3);
}

:deep(.el-button--primary:active) {
  background: var(--el-color-primary-dark-2);
  border: 1px solid var(--el-color-primary-dark-2);
}

/* 输入框样式优化 */
:deep(.el-input__wrapper) {
  border-radius: 10px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
}

/* 下拉框样式优化 */
:deep(.el-select) {
  border-radius: 10px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 10px;
}

/* 日期选择器样式优化 */
:deep(.el-date-editor) {
  border-radius: 10px;
}

:deep(.el-date-editor:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 排序图标样式 */
.sort-header {
  user-select: none;
}

.sort-header:hover {
  color: var(--el-color-primary);
}

.sort-icon {
  transition: all 0.2s ease;
}

.sort-icon.active {
  color: var(--el-color-primary);
  font-weight: bold;
}

/* ========================================
 * BETA测试 - 波动特效
 * 功能：表格行涌现动画，带放大回弹效果
 * 时间：单行动画0.30s，行间间隔0.05s，总波动≈1.0s（按20行覆盖）
 * 状态：测试中，可能影响性能
 * ======================================== */

/* 涌现动画样式 - 从上到下涌现，带放大回弹效果 */
:deep(.el-table__body tr) {
  animation: emergeIn 0.30s ease-out forwards;
  opacity: 0;
  transform: translateY(-20px);
  transform-origin: center center;
  will-change: transform, opacity;
}

/* 确保每行独立动画（覆盖20行） */
:deep(.el-table__body tr:nth-child(1)) { animation-delay: 0.05s; }
:deep(.el-table__body tr:nth-child(2)) { animation-delay: 0.10s; }
:deep(.el-table__body tr:nth-child(3)) { animation-delay: 0.15s; }
:deep(.el-table__body tr:nth-child(4)) { animation-delay: 0.20s; }
:deep(.el-table__body tr:nth-child(5)) { animation-delay: 0.25s; }
:deep(.el-table__body tr:nth-child(6)) { animation-delay: 0.30s; }
:deep(.el-table__body tr:nth-child(7)) { animation-delay: 0.35s; }
:deep(.el-table__body tr:nth-child(8)) { animation-delay: 0.40s; }
:deep(.el-table__body tr:nth-child(9)) { animation-delay: 0.45s; }
:deep(.el-table__body tr:nth-child(10)) { animation-delay: 0.50s; }
:deep(.el-table__body tr:nth-child(11)) { animation-delay: 0.55s; }
:deep(.el-table__body tr:nth-child(12)) { animation-delay: 0.60s; }
:deep(.el-table__body tr:nth-child(13)) { animation-delay: 0.65s; }
:deep(.el-table__body tr:nth-child(14)) { animation-delay: 0.70s; }
:deep(.el-table__body tr:nth-child(15)) { animation-delay: 0.75s; }
:deep(.el-table__body tr:nth-child(16)) { animation-delay: 0.80s; }
:deep(.el-table__body tr:nth-child(17)) { animation-delay: 0.85s; }
:deep(.el-table__body tr:nth-child(18)) { animation-delay: 0.90s; }
:deep(.el-table__body tr:nth-child(19)) { animation-delay: 0.95s; }
:deep(.el-table__body tr:nth-child(20)) { animation-delay: 1.00s; }

@keyframes emergeIn {
  0% {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  60% {
    opacity: 1;
    transform: translateY(0) scale(1.05);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 移除动态延迟，使用固定延迟 */

/* 深色模式下的涌现效果 */

/* 深色模式下的独立动画延迟 */

/* ========================================
 * BETA测试 - 波动特效 结束
 * ======================================== */
</style>